import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
  Search,
  Filter,
  RefreshCw,
  Grid,
  List,
  SortAsc,
  SortDesc
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/Card'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { Badge } from '../components/ui/Badge'
import { PluginCard } from '../components/PluginCard'

interface MarketItem {
  name: string
  manifest: string
  enabled: boolean
}

interface PluginManifest {
  name: string
  version: string
  description?: string
  author?: string
  icon?: string
  tags?: string[]
}

interface PluginManagementProps {
  market: MarketItem[]
  onTogglePlugin: (plugin: MarketItem) => void
  onConfigurePlugin: (plugin: MarketItem) => void
  onRescanPlugins: () => void
  rescanLoading: boolean
}

type SortOption = 'name' | 'author' | 'version' | 'status'
type ViewMode = 'grid' | 'list'

export function PluginManagement({
  market,
  onTogglePlugin,
  onConfigurePlugin,
  onRescanPlugins,
  rescanLoading
}: PluginManagementProps) {
  const { t } = useTranslation()
  const [manifests, setManifests] = useState<Record<string, PluginManifest>>({})
  const [searchQuery, setSearchQuery] = useState('')
  const [filterStatus, setFilterStatus] = useState<'all' | 'enabled' | 'disabled'>('all')
  const [sortBy, setSortBy] = useState<SortOption>('name')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc')
  const [viewMode, setViewMode] = useState<ViewMode>('grid')

  // Load plugin manifests
  useEffect(() => {
    const loadManifests = async () => {
      const manifestPromises = market.map(async (plugin) => {
        try {
          const res = await fetch(plugin.manifest)
          const manifest = await res.json()
          return { id: plugin.name, manifest }
        } catch (error) {
          console.warn(`Failed to load manifest for ${plugin.name}:`, error)
          return { id: plugin.name, manifest: null }
        }
      })
      
      const results = await Promise.all(manifestPromises)
      const manifestMap: Record<string, PluginManifest> = {}
      results.forEach(({ id, manifest }) => {
        if (manifest) manifestMap[id] = manifest
      })
      setManifests(manifestMap)
    }

    if (market.length > 0) {
      loadManifests()
    }
  }, [market])

  // Filter and sort plugins
  const filteredAndSortedPlugins = market
    .filter((plugin) => {
      const manifest = manifests[plugin.name]
      const searchText = `${manifest?.name || plugin.name} ${manifest?.description || ''} ${manifest?.author || ''}`.toLowerCase()
      const matchesSearch = searchText.includes(searchQuery.toLowerCase())
      
      const matchesFilter = 
        filterStatus === 'all' || 
        (filterStatus === 'enabled' && plugin.enabled) ||
        (filterStatus === 'disabled' && !plugin.enabled)
      
      return matchesSearch && matchesFilter
    })
    .sort((a, b) => {
      const manifestA = manifests[a.name]
      const manifestB = manifests[b.name]
      
      let valueA: string | number = ''
      let valueB: string | number = ''
      
      switch (sortBy) {
        case 'name':
          valueA = manifestA?.name || a.name
          valueB = manifestB?.name || b.name
          break
        case 'author':
          valueA = manifestA?.author || ''
          valueB = manifestB?.author || ''
          break
        case 'version':
          valueA = manifestA?.version || '0.0.0'
          valueB = manifestB?.version || '0.0.0'
          break
        case 'status':
          valueA = a.enabled ? 1 : 0
          valueB = b.enabled ? 1 : 0
          break
      }
      
      if (typeof valueA === 'string' && typeof valueB === 'string') {
        return sortOrder === 'asc' 
          ? valueA.localeCompare(valueB)
          : valueB.localeCompare(valueA)
      }
      
      return sortOrder === 'asc' 
        ? (valueA as number) - (valueB as number)
        : (valueB as number) - (valueA as number)
    })

  const enabledCount = market.filter(p => p.enabled).length
  const disabledCount = market.length - enabledCount

  const toggleSort = (option: SortOption) => {
    if (sortBy === option) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(option)
      setSortOrder('asc')
    }
  }

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{t('plugins.title')}</h1>
          <p className="text-muted-foreground mt-1">
            {t('plugins.subtitle')}
          </p>
        </div>

        <Button
          onClick={onRescanPlugins}
          disabled={rescanLoading}
          loading={rescanLoading}
          className="flex items-center space-x-2"
        >
          <RefreshCw className="h-4 w-4" />
          <span>{t('plugins.rescanPlugins')}</span>
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="text-2xl font-bold">{market.length}</div>
            <p className="text-sm text-muted-foreground">{t('plugins.stats.total')}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-2xl font-bold text-green-600">{enabledCount}</div>
            <p className="text-sm text-muted-foreground">{t('plugins.stats.enabled')}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-2xl font-bold text-gray-500">{disabledCount}</div>
            <p className="text-sm text-muted-foreground">{t('plugins.stats.disabled')}</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters and Controls */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col lg:flex-row gap-4">
            {/* Search */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder={t('plugins.filters.searchPlaceholder')}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            {/* Filter by status */}
            <div className="flex items-center space-x-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <select
                value={filterStatus}
                onChange={(e) => setFilterStatus(e.target.value as any)}
                className="input w-32"
              >
                <option value="all">{t('plugins.filters.allStatus')}</option>
                <option value="enabled">{t('plugins.filters.enabled')}</option>
                <option value="disabled">{t('plugins.filters.disabled')}</option>
              </select>
            </div>

            {/* Sort */}
            <div className="flex items-center space-x-2">
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as SortOption)}
                className="input w-32"
              >
                <option value="name">{t('plugins.filters.sortBy.name')}</option>
                <option value="author">{t('plugins.filters.sortBy.author')}</option>
                <option value="version">{t('plugins.filters.sortBy.version')}</option>
                <option value="status">{t('plugins.filters.sortBy.status')}</option>
              </select>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
              >
                {sortOrder === 'asc' ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />}
              </Button>
            </div>

            {/* View mode */}
            <div className="flex items-center space-x-1 border rounded-md p-1">
              <Button
                variant={viewMode === 'grid' ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setViewMode('grid')}
                className="h-8 w-8 p-0"
              >
                <Grid className="h-4 w-4" />
              </Button>
              <Button
                variant={viewMode === 'list' ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setViewMode('list')}
                className="h-8 w-8 p-0"
              >
                <List className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Plugin List */}
      {filteredAndSortedPlugins.length > 0 ? (
        <div className={
          viewMode === 'grid' 
            ? 'grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6'
            : 'space-y-4'
        }>
          {filteredAndSortedPlugins.map((plugin) => (
            <PluginCard
              key={plugin.name}
              plugin={plugin}
              manifest={manifests[plugin.name]}
              onToggle={() => onTogglePlugin(plugin)}
              onConfigure={() => onConfigurePlugin(plugin)}
              compact={viewMode === 'list'}
            />
          ))}
        </div>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>{t('plugins.noPluginsFound.title')}</CardTitle>
            <CardDescription>
              {searchQuery || filterStatus !== 'all'
                ? t('plugins.noPluginsFound.withFilters')
                : t('plugins.noPluginsFound.withoutFilters')
              }
            </CardDescription>
          </CardHeader>
          <CardContent>
            {searchQuery || filterStatus !== 'all' ? (
              <div className="flex space-x-2">
                <Button variant="outline" onClick={() => setSearchQuery('')}>
                  {t('plugins.noPluginsFound.clearSearch')}
                </Button>
                <Button variant="outline" onClick={() => setFilterStatus('all')}>
                  {t('plugins.noPluginsFound.clearFilters')}
                </Button>
              </div>
            ) : (
              <Button onClick={onRescanPlugins} loading={rescanLoading}>
                {t('plugins.noPluginsFound.rescanForPlugins')}
              </Button>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  )
}
